import React, { useState, useEffect } from 'react';
import type { TableProps } from 'antd';
import {
  Form, Input, Select, Button, Popconfirm, Table, message, Switch, Space, Image, Modal, Upload
} from 'antd';
import {
  SearchOutlined, ReloadOutlined, PlusOutlined, EditOutlined, DeleteOutlined, UploadOutlined
} from '@ant-design/icons';
import { dataGet, dataDel, dataAdd, imageFile } from '@/api/goodstype';
import './module.css/module.goodstype.css';
const { Option } = Select;
import { path } from '@/config/index'

interface CategoryType {
  id: string | number;
  key: string;
  title: string;
  img: string;
  status: number; // 1:开启, 0:关闭
  homeview: number; // 1:显示, 0:不显示
  sort: number;
}

const Goodstype: React.FC = () => {
  const [form] = Form.useForm();
  const [searchForm] = Form.useForm();
  const [data, setData] = useState<CategoryType[]>([]);
  const [loading, setLoading] = useState(false);
  // const [editingKey, setEditingKey] = useState('');
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 100,
    total: 0,
  });
  // 控制弹窗显隐
  const [isModalVisible, setIsModalVisible] = useState(false);
  // 标记是新增还是编辑
  const [isAdd, setIsAdd] = useState(true);
  // 存储当前编辑项的id
  const [currentEditId, setCurrentEditId] = useState('');
  // 上传的图片URL
  const [imageUrl, setImageUrl] = useState<string>('');

  // 获取商品分类列表数据
  const fetchCategoryList = async (pageParams = { current: 1, pageSize: 100 }, searchParams = {}) => {
    setLoading(true);
    try {
      const params = {
        current: pageParams.current,
        pageSize: pageParams.pageSize,
        ...searchParams
      };

      const response = await dataGet(params);
      if (response.code === 1) {
        const records = response.data.list;
        const categoryData = Array.isArray(records) ? records.map((item: any) => ({
          ...item,
          key: item.id?.toString() || Math.random().toString(),
        })) : [];

        setData(categoryData);

        setPagination({
          current: response.data?.current || pageParams.current,
          pageSize: response.data?.pageSize || pageParams.pageSize,
          total: response.data?.total || 0,
        });
      } else {
        message.error(response.msg || '获取商品分类列表失败');
      }
    } catch (error) {
      console.error('获取商品分类列表失败:', error);
      message.error('获取商品分类列表失败，请检查网络连接');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchCategoryList({ current: 1, pageSize: 100 });
  }, []);

  // 图片上传处理
  const handleUpload = async (file: File) => {
    try {
      const formData = new FormData();
      formData.append('file', file);

      // 这里假设 imageFile 是上传API，返回上传后的图片URL
      const response = await imageFile(formData);
      if (response.code === 1) {
        setImageUrl(response.data.url);
        form.setFieldsValue({ img: response.data.url });
        message.success('上传成功');
        console.log(response.data.url);

        return false; // 阻止默认上传行为
      } else {
        message.error(response.msg || '上传失败');
        return false;
      }
    } catch (error) {
      console.error('上传失败:', error);
      message.error('上传失败');
      return false;
    }
  };

  // 上传前的校验
  const beforeUpload = (file: File) => {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) {
      message.error('只能上传 JPG/PNG 格式的图片!');
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      message.error('图片必须小于 2MB!');
    }
    return isJpgOrPng && isLt2M;
  };

  // 搜索处理
  const handleSearch = () => {
    const values = searchForm.getFieldsValue();
    const searchParams = {
      title: values.name,
      status: values.status,
      homeview: values.homeview
    };

    const filteredParams = Object.fromEntries(
      Object.entries(searchParams).filter(([_, value]) => value !== undefined && value !== '')
    );

    fetchCategoryList({ current: 1, pageSize: pagination.pageSize }, filteredParams);
  };

  // 重置搜索 - 同时重置复选框选中状态
  const handleReset = () => {
    searchForm.resetFields();
    // 重置复选框选中状态
    setSelectedRowKeys([]);
    fetchCategoryList({ current: 1, pageSize: pagination.pageSize });
  };

  // 表格分页变化处理
  const handleTableChange = (pagination: any) => {
    const values = searchForm.getFieldsValue();
    const searchParams = {
      title: values.name,
      status: values.status,
      homeview: values.homeview
    };

    const filteredParams = Object.fromEntries(
      Object.entries(searchParams).filter(([_, value]) => value !== undefined && value !== '')
    );

    // 分页变化时重置复选框选中状态
    setSelectedRowKeys([]);

    fetchCategoryList(
      {
        current: pagination.current,
        pageSize: pagination.pageSize
      },
      filteredParams
    );
  };

  // 删除分类
  const handleDelete = async (id: string | number) => {
    try {
      const response = await dataDel({ ids: id });
      if (response.code === 1) {
        message.success('删除成功');
        // 删除后重置复选框选中状态
        setSelectedRowKeys([]);
        fetchCategoryList(
          { current: pagination.current, pageSize: pagination.pageSize },
          searchForm.getFieldsValue()
        );
      } else {
        message.error(response.msg || '删除失败');
      }
    } catch (error) {
      console.error('删除分类失败:', error);
      message.error('删除失败');
    }
  };

  // 状态显示组件
  const StatusDisplay = ({ status }: { status: number }) => (
    <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
      {status === 1 ? (
        <>
          <div style={{
            width: '8px',
            height: '8px',
            borderRadius: '50%',
            backgroundColor: '#52c41a',
            marginRight: '8px'
          }} />
          <span>开启</span>
        </>
      ) : (
        <span>关闭</span>
      )}
    </div>
  );

  // 首页显示状态组件
  const HomeviewDisplay = ({ homeview }: { homeview: number }) => (
    <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
      {homeview === 1 ? (
        <>
          <div style={{
            width: '8px',
            height: '8px',
            borderRadius: '50%',
            backgroundColor: '#52c41a',
            marginRight: '8px'
          }} />
          <span>显示</span>
        </>
      ) : (
        <span>不显示</span>
      )}
    </div>
  );

  // 表格列定义
  const columns: TableProps<CategoryType>['columns'] = [
    {
      title: '序号',
      dataIndex: 'index',
      align: 'center',
      width: 60,
      render: (_, __, index) => index + 1 + (pagination.current - 1) * pagination.pageSize,
    },
    {
      title: '分类名称',
      dataIndex: 'title',
      align: 'center',
      width: 120,
    },
    {
      title: '分类图片',
      dataIndex: 'img',
      align: 'center',
      width: 100,
      render: (img) => (
        <Image
          width={50}
          height={50}
          src={img}
          alt="分类图片"
          style={{ objectFit: 'cover' }}
          fallback="https://via.placeholder.com/50"
        />
      ),
    },
    {
      title: '状态',
      dataIndex: 'status',
      align: 'center',
      width: 100,
      render: (status) => <StatusDisplay status={status} />,
    },
    {
      title: '首页显示',
      dataIndex: 'homeview',
      align: 'center',
      width: 100,
      render: (homeview) => <HomeviewDisplay homeview={homeview} />,
    },
    {
      title: '排序',
      dataIndex: 'sort',
      align: 'center',
      width: 80,
    },
    {
      title: '操作',
      align: 'center',
      dataIndex: 'operation',
      width: 120,
      render: (_, record) => (
        <Space>
          <Button
            type="link"
            style={{ padding: '0 4px', border: '1px solid #1890ff' }}
            size="small"
            icon={<EditOutlined />}
            onClick={() => handleEdit(record)}
          >
            编辑
          </Button>
          <Popconfirm
            title="确定要删除这个分类吗？"
            onConfirm={() => handleDelete(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Button
              type="link"
              style={{ padding: '0 4px', border: '1px solid #ff4d4f' }}
              danger
              size="small"
              icon={<DeleteOutlined />}
            >
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  // 打开新增/编辑弹窗
  const showModal = (isAddMode: boolean, record?: CategoryType) => {
    setIsModalVisible(true);
    setIsAdd(isAddMode);
    if (!isAddMode && record) {
      form.setFieldsValue({
        title: record.title,
        img: record.img,
        status: record.status === 1,
        homeview: record.homeview === 1,
        sort: record.sort
      });
      setImageUrl(record.img);
      setCurrentEditId(record.id.toString());
    } else {
      form.resetFields();
      setImageUrl('');
      setCurrentEditId('');
    }
    // 打开弹窗时重置复选框选中状态
    setSelectedRowKeys([]);
  };

  // 关闭弹窗
  const handleCancel = () => {
    setIsModalVisible(false);
    form.resetFields();
    setImageUrl('');
    setCurrentEditId('');
  };

  // 提交表单
  const handleOk = async () => {
    try {
      const values = await form.validateFields();
      const params = {
        ...values,
        status: values.status ? 1 : 0, // 将布尔值转换为数字
        homeview: values.homeview ? 1 : 0, // 将布尔值转换为数字
        id: isAdd ? undefined : currentEditId
      };
      const response = await dataAdd(params);
      if (response.code === 1) {
        message.success(isAdd ? '新增成功' : '编辑成功');
        setIsModalVisible(false);
        // 提交成功后重置复选框选中状态
        setSelectedRowKeys([]);
        fetchCategoryList({ current: pagination.current, pageSize: pagination.pageSize }, searchForm.getFieldsValue());
      } else {
        message.error(response.msg || (isAdd ? '新增失败' : '编辑失败'));
      }
    } catch (error) {
      console.error('表单校验或提交失败:', error);
    }
  };

  // 处理编辑
  const handleEdit = (record: CategoryType) => {
    showModal(false, record);
  };

  const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
    setSelectedRowKeys(newSelectedRowKeys);
  };

  const rowSelection = {
    selectedRowKeys,
    onChange: onSelectChange,
  };

  return (
    <div className='white' style={{ padding: '20px' }}>
      <div className='teacher'>商品分类</div>

      <div className='search'>
        <Form
          form={searchForm}
          layout="horizontal"
          colon={false}
          style={{ width: '83%' }}
        >
          <div className='searchList'>
            <Form.Item name="name" label="分类名称">
              <Input placeholder="请输入分类名称" style={{ width: '225px' }} />
            </Form.Item>
            <Form.Item name="status" label="分类状态">
              <Select placeholder="请选择分类状态" style={{ width: '225px' }}>
                <Option value="1">开启</Option>
                <Option value="0">关闭</Option>
              </Select>
            </Form.Item>
            <Form.Item name="homeview" label="首页显示">
              <Select placeholder="请选择首页显示" style={{ width: '225px' }}>
                <Option value="1">显示</Option>
                <Option value="0">不显示</Option>
              </Select>
            </Form.Item>
          </div>
        </Form>

        <div style={{ height: '30px', width: '1px', background: '#999999' }}></div>

        <div className='buttons'>
          <Button
            type="primary"
            onClick={handleSearch}
            style={{ width: '75px', background: '#165DFF' }}
            icon={<SearchOutlined />}
          >
            查询
          </Button>
          <Button
            onClick={handleReset}
            style={{ width: '75px' }}
            icon={<ReloadOutlined />}
          >
            重置
          </Button>
        </div>
      </div>
      <div className='line'></div>

      <div className='buttonBox'>
        <div className='refresh'>
          <Button type="primary" icon={<PlusOutlined />} onClick={() => showModal(true)}>
            新建
          </Button>
        </div>
        <div>
          <img
            src="./refresh.png"
            alt="refresh"
            onClick={handleReset}
            className='w20'
            style={{ cursor: 'pointer' }}
          />
        </div>
      </div>

      <Table<CategoryType>
        rowSelection={rowSelection}
        loading={loading}
        dataSource={data}
        columns={columns}
        pagination={{
          current: pagination.current,
          pageSize: pagination.pageSize,
          total: pagination.total,
          showSizeChanger: true,
          showQuickJumper: true,
          showTotal: (total) => `共 ${total} 条记录`,
        }}
        onChange={handleTableChange}
        scroll={{ x: 800 }}
      />

      <Modal
        title={isAdd ? '新建商品分类' : '编辑商品分类'}
        open={isModalVisible}
        onOk={handleOk}
        onCancel={handleCancel}
        okText="确定"
        cancelText="取消"
        width={600}
        className="category-modal"
        footer={[
          <Button key="cancel" onClick={handleCancel} style={{ width: 80, height: 32 }}>
            取消
          </Button>,
          <Button key="submit" type="primary" onClick={handleOk} style={{ width: 80, height: 32 }}>
            确定
          </Button>,
        ]}
      >
        <Form
          form={form}
          layout="horizontal"
          name="categoryForm"
          colon={false}
          className="category-form"
        >
          <Form.Item
            name="title"
            label="分类名称"
            rules={[
              { required: true, message: '请输入分类名称' },
              // 添加正则校验，不允许全空格或空值
              {
                pattern: /^\S+.*$/,
                message: '请输入分类名称'
              },
              // 新增去重校验，先检查值是否存在
              {
                validator: async (_, value) => {
                  // 先检查值是否存在，不存在则不进行校验
                  if (!value) return;

                  // 去除首尾空格再校验是否已存在
                  const trimmedValue = value.trim();
                  // 查找是否已存在同名分类（排除当前编辑的分类）
                  const isExist = data.some(
                    item =>
                      item.title?.trim() === trimmedValue && // 增加可选链操作符防止item.title为undefined
                      (isAdd || (currentEditId && item.id.toString() !== currentEditId))
                  );
                  if (isExist) {
                    throw new Error('该分类名称已存在');
                  }
                }
              }
            ]}
            className="form-item-custom"
            labelCol={{ span: 4 }}
            wrapperCol={{ span: 20 }}
          >
            <Input
              placeholder="请输入分类名称"
              style={{ height: '32px' }}
            />
          </Form.Item>

          <Form.Item
            name="homeview"
            label="首页显示"
            valuePropName="checked"
            className="form-item-custom switch-item"
            labelCol={{ span: 4 }}
            wrapperCol={{ span: 20 }}
          >
            <Switch />
          </Form.Item>

          <Form.Item
            name="img"
            label="分类图片"
            rules={[{ required: true, message: '请上传分类图片' }]}
            className="form-item-custom"
            labelCol={{ span: 4 }}
            wrapperCol={{ span: 20 }}
          >
            <Upload
              name="file"
              listType="picture-card"
              showUploadList={false}
              beforeUpload={beforeUpload}
              customRequest={({ file }) => handleUpload(file as File)}
              accept="image/*"
              className="upload-custom"
            >
              {imageUrl ? (
                <div className="upload-image-preview">
                  <img
                    src={imageUrl.startsWith('http') || imageUrl.startsWith('https') ? imageUrl : path + imageUrl}
                    alt="分类图片"
                    style={{ width: '100%', height: '100%', objectFit: 'cover' }}
                  />
                  <div className="upload-replace-text">重新上传</div>
                </div>
              ) : (
                <div className="upload-placeholder">
                  <PlusOutlined className="upload-icon" />
                  <div className="upload-text">上传图片</div>
                </div>
              )}
            </Upload>
          </Form.Item>

          <Form.Item
            name="status"
            label="状态"
            valuePropName="checked"
            className="form-item-custom switch-item"
            labelCol={{ span: 4 }}
            wrapperCol={{ span: 20 }}
          >
            <Switch />
          </Form.Item>

          <Form.Item
            name="sort"
            label="排序"
            rules={[{ required: true, message: '请输入排序' }]}
            className="form-item-custom"
            labelCol={{ span: 4 }}
            wrapperCol={{ span: 20 }}
          >
            <Input
              type="number"
              placeholder="0"
              style={{ height: '32px' }}
            />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default Goodstype;
